package com.jinyi.wwdeng.ui.login.impl

import android.content.Context
import com.jinyi.base.mvp.BasePresenter
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.analysis.TestAnalysisAddEvent
import com.jinyi.wwdeng.analysis.TestAnalysisInit
import com.jinyi.wwdeng.ui.login.contract.LoginContract
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/28 11:47
 * @Annotation：Presenter 实现类
 */
class LoginPresenterImpl: BasePresenter<LoginContract.View?,LoginModelImpl?>(),LoginContract.Presenter {

    override fun createModel(): LoginModelImpl {
        return LoginModelImpl(this)
    }

    /***
     * 发送验证码
     * @param param
     */
    fun sendSmsCodeRequest(mobile: String){
        if (isViewDestory()) {
            return
        }
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val commonData = JSONObject(AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_COMMON))
        val customize = commonData.optJSONObject("customize")
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (mobile == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            //保存用户登录状态为已登录
            AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_LOGIN,true)
            //保存用户id
            // TODO: 待完善 缺少 UserId
            AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_USERID,accItem.optString("accUid"))
            //保存用户Token
            AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_TOKEN,accItem.optString("accTk"))
            //初始化analysis lib 赋值 用户id 和 token
            TestAnalysisInit.initAnalysisLibAtLoginSuccess()

            mvpView!!.showLoginSuccess()
            return
        }
        model!!.sendSmsCodeRequest(mobile)
    }

    /**
     * 登录
     * @param params
     */
    fun loginRequest(mobile: String,code: String){
        if (isViewDestory()) {
            return
        }
        model!!.loginRequest(mobile,code,"NO")
    }

    /**
     * 验证码发送成功
     */
    override fun onSendSmsSuccess(data: JSONObject) {
        if (isViewDestory()) {
            return
        }
        mvpView!!.hideLoading()
        when(data.optInt("code")){
            0 -> {//发送成功
                val obj = data.optJSONObject("obj")
                //是否直接登录
                val directLoginFlag = obj?.optString("directLoginFlag", "NO")
                if (directLoginFlag == "YES"){
                    //直接执行登录接口  code: 0000
                    model!!.loginRequest(mvpView!!.getMobile(),"0000",directLoginFlag)
                    return
                }
                mvpView!!.showSendSmsSuccess(data)
            }
            else -> {
                val msg = data.optString("msg")
                mvpView!!.showToast(msg)
            }
        }
    }

    /**
     * 登录成功
     */
    override fun onLoginSuccess(data: JSONObject) {
        if (isViewDestory()) {
            return
        }
        /**
         * {
         *                    "code":"0000",
         *                    "msg":"success",
         *                    "obj":{
         *                      "isAdSource":"NO",
         *                      "type":"REGISTER",
         *                      "userId":"1234162819029677945",
         *                      "token":"e48cc4b124f2445773c7b98599389d3d"
         *                    }
         *                  }
         */

        when(data.optInt("code")){
            0 -> {//登录成功
                val obj = data.optJSONObject("obj")
                val userId = obj.optString("userId")
                val userToken = obj.optString("token")
                val type = obj.optString("type")
                //保存用户登录状态为已登录
                AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_LOGIN,true)
                //保存用户id
                AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_USERID,userId)
                //保存用户Token
                AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_TOKEN,userToken)
                //初始化analysis lib 赋值 用户id 和 token
                TestAnalysisInit.initAnalysisLibAtLoginSuccess()

                //登录类型 == 注册，需要打点
                if (type == "REGISTER"){
                    TestAnalysisAddEvent.addRegisterEvent()
                }
                mvpView!!.showLoginSuccess()
            }
            else -> {
                val msg = data.optString("msg")
                mvpView!!.showToast(msg)
                mvpView!!.showLoginFailure(data)
            }
        }
    }

    /**
     * 登录失败
     */
    override fun onLoginFailure(data: JSONObject) {

    }

    override fun onFailureData(msg: String) {
        if (isViewDestory()) {
            return
        }
        mvpView!!.showToast(msg)
    }

    override val context: Context?
        get() = if (!isViewDestory()) {
            mvpView!!.getContext()
        } else null
}